using System;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;

namespace RibbonCustomization.Features.RibbonDemo
{
    [Guid("7ff0f542-09ff-4946-a3a0-61670d88f276")]
    public class RibbonDemoEventReceiver : SPFeatureReceiver
    {
        const string NodeKey = "RibbonDemoEventReceiver";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite siteCollection = (SPSite)properties.Feature.Parent;
            SPWeb site = siteCollection.RootWeb;
            SPNavigationNode node = site.Navigation.TopNavigationBar.AddAsLast(
                new SPNavigationNode("Ribbon Demos", "RibbonPages/OverviewPage.aspx"));
            site.Properties[NodeKey] = node.Id.ToString();
            site.Update();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite siteCollection = (SPSite)properties.Feature.Parent;
            SPWeb site = siteCollection.RootWeb;
            if (site.Properties.ContainsKey(NodeKey))
            {
                int nodeID = Int32.Parse(site.Properties[NodeKey]);
                SPNavigationNode node = site.Navigation.GetNodeById(nodeID);
                if (node != null)
                {
                    node.Delete();
                }
                site.Properties.Remove(NodeKey);
            }
        }
    }
}
